using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.productpurchaseprices;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.productpurchaseprices
{
    /// <summary>
    /// 添加商品采购价格命令处理器
    /// </summary>
    public class AddProductPurchasePriceCommandHandler : IRequestHandler<AddProductPurchasePriceCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ProductPurchasePrice> _productPurchasePriceRepository;
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddProductPurchasePriceCommandHandler> _logger;

        public AddProductPurchasePriceCommandHandler(
            IBaseRepository<ProductPurchasePrice> productPurchasePriceRepository,
            IBaseRepository<Supplier> supplierRepository,
            IMapper mapper,
            ILogger<AddProductPurchasePriceCommandHandler> logger)
        {
            _productPurchasePriceRepository = productPurchasePriceRepository;
            _supplierRepository = supplierRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理添加商品采购价格命令
        /// </summary>
        /// <param name="request">添加商品采购价格命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(AddProductPurchasePriceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证供应商是否存在
                var supplier = await _supplierRepository.GetAll()
                    .FirstOrDefaultAsync(s => s.Id == request.SupplierId && !s.IsDeleted, cancellationToken);

                if (supplier == null)
                {
                    return ApiResult<int>.Error("供应商不存在");
                }

                // 验证日期范围
                if (request.StartDate >= request.EndDate)
                {
                    return ApiResult<int>.Error("开始日期必须早于结束日期");
                }

                // 验证同一供应商下是否存在相同商品名称和规格的价格记录
                var existingPrice = await _productPurchasePriceRepository.GetAll()
                    .FirstOrDefaultAsync(p => 
                        p.SupplierId == request.SupplierId && 
                        p.ProductName == request.ProductName && 
                        p.Specification == request.Specification && 
                        !p.IsDeleted, cancellationToken);

                if (existingPrice != null)
                {
                    return ApiResult<int>.Error("该供应商下已存在相同商品名称和规格的价格记录");
                }

                // 手动创建实体，避免导航属性问题
                var productPurchasePrice = new ProductPurchasePrice
                {
                    SupplierId = request.SupplierId,
                    ProductName = request.ProductName,
                    Specification = request.Specification,
                    MeasurementUnit = request.MeasurementUnit,
                    InvoicePrice = request.InvoicePrice,
                    SettlementPrice = request.SettlementPrice,
                    Discount = request.Discount,
                    PublicPrice = request.PublicPrice,
                    StartDate = request.StartDate,
                    EndDate = request.EndDate,
                    SchemeName = request.SchemeName,
                    Remarks = request.Remarks
                };

                // 设置创建时间
                productPurchasePrice.CreatedTime = DateTime.Now;

                // 添加商品采购价格
                var result = await _productPurchasePriceRepository.AddAsync(productPurchasePrice);

                if (result > 0)
                {
                    _logger.LogInformation("成功添加商品采购价格，ID: {PriceId}, 供应商: {SupplierName}, 商品: {ProductName}", 
                        productPurchasePrice.Id, supplier.SupplierName, request.ProductName);
                    
                    return ApiResult<int>.Success(productPurchasePrice.Id, "商品采购价格添加成功");
                }
                else
                {
                    _logger.LogError("添加商品采购价格失败，供应商: {SupplierName}, 商品: {ProductName}", 
                        supplier.SupplierName, request.ProductName);
                    
                    return ApiResult<int>.Error("商品采购价格添加失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加商品采购价格时发生异常，供应商ID: {SupplierId}, 商品: {ProductName}", 
                    request.SupplierId, request.ProductName);
                
                return ApiResult<int>.Error("添加商品采购价格时发生异常");
            }
        }
    }
} 